var j$ = jQuery;

var Page ={
    Map: '',
    GPSPoints: '',
    GPSBounds: '',
    Poly: '',
    Uploader: '',
    uploaderUrl: $("#uploadify_script").attr("data-url"),
    PreviewPopup: $("#preview-popup"),
    initPhotoEvents: function () {
        $('#filelist').on('click', '.btn-del', Page.removePhoto);
        $('#filelist').on('hover', '.photo-tile', Page.showPhotoPreview);
        $('#filelist').on('mouseleave', '.photo-tile', Page.hidePhotoPreview);
        Page.photoPrivacyEvents();
    },
    photoPrivacyEvents: function () {
        $('#filelist').on('click', '.privacy', Page.openPrivacySelect);
        $('#filelist').on('mouseleave', '.privacy-list', Page.hidePrivacySelect);
        $('#filelist').on('click', '.privacy-list a', Page.changePhotoPrivacy);
    },
    removePhoto: function (e) {
        e.preventDefault();
        Page.disableDoneButton();
        var _this = $(this);
        var _tile = _this.parents('.photo-tile');
        var _id = _tile.attr('data-file-id');
        _tile.css('opacity', 0.3);
        $.ajax({
            url: _this.attr("data-del-url"),
            type: 'DELETE',
            success: function() {
                Page.PreviewPopup.stop(true, true).fadeOut();
                _tile.fadeOut("slow", function() {
                    _tile.remove();
                    Page.Uploader.removeFile(_id, true);
                    Page.Uploader.refresh();
                    Page.refreshDoneButton();
                });
            },
            error: function() {
                _tile.css('opacity', 1);
            }
        });
    },
    showPhotoPreview: function (e) {
        var _tile = $(this);
        if ( _tile.hasClass('upload-tile') ) {
            return;
        }else if ( _tile.attr('data-finished') === '1' ) {
            var _onTheLeft = $('.photo-tile').not('.photo-tile-tpl')
                .index(_tile) % 7 < 4;
            var _img = _tile.find('.photo').attr('data-src');
            Page.PreviewPopup.find('img').attr('src', _img);
            Page.PreviewPopup.css({
                    'left': (_tile.offset().left + (_onTheLeft? 162: -238)),
                    'top': _tile.offset().top
                })
                .stop(true, true).delay(800).fadeIn(200, function() {
                    Page.PreviewPopup.removeClass('hidden');
                });
        }
    },
    hidePhotoPreview: function (e) {
        if ( $(this).hasClass('upload-tile') ) {
            return;
        }
        Page.PreviewPopup.stop(true, true).hide();
    },
    openPrivacySelect: function (e) {
        e.preventDefault();
        $(this).next('.privacy-list').removeClass('hidden');
    },
    hidePrivacySelect: function () {
        $(this).addClass('hidden');
    },
    changePhotoPrivacy: function (e) {
        e.preventDefault();
        var _this = $(this);
        var _privacy = _this.text();
        var _privacyId = _this.data('id');
        _this.parent('li').addClass('cur').siblings('li').removeClass('cur');
        _this.parents('.privacy-list').addClass('hidden')
            .prev('.privacy').html(_privacy)
            .parent('.photo-tile').attr('data-privacy', _privacyId);
    },
    addTimezoneUrl: function () {
        var _select = $("#timezone");
        var _argu = "&tz=" + _select.val();
        $("#btn-next").attr("url", Page.uploaderUrl + _argu);
    },
    disableDoneButton: function () {
        $('#btn-next').addClass('disabled');
    },
    refreshDoneButton: function () {
        Page.addTimezoneUrl();
        var photo_upload = false;
        var _photos = $("#filelist .photo-tile[data-finished]");
        for (var i = 0; i < _photos.length; i++) {
            if ($(_photos[i]).attr("data-finished") == "0") {
                photo_upload = true;
                break;
            }
        }

        if(Page.GPSPoints || (!photo_upload && $("#filelist .photo-tile[data-wp-id]").length > 0)) {
            $("#btn-next").removeClass("disabled");
        } else {
            $("#btn-next").addClass("disabled");
        }
    },
    initUploadEvents: function () {
        var _updateUploadProcess = function(obj, value) {
            obj.find(".progress-text").text(value + "%");
            obj.find(".progress-bar").css('height', (100-value)+'%');
        };

        var _startFakeUploadProcess = function(obj, interval) {
            var current = parseInt(obj.find(".upload-progress-bar").progressbar("value"));
            var offset = parseInt(Math.random() * 15 + 5);
            if(current < 90) {
                _updateUploadProcess(obj, Math.min(90, current + offset));

                var timer = setTimeout(function() {
                    _startFakeUploadProcess(obj, interval);
                }, interval);
            }
        };

        Page.Uploader = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,

            // swf文件路径
            swf: '/static/new/plugins/Moxie.swf?v=20140617',

            // 文件接收服务端。
            server: Page.uploaderUrl,

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#pickfiles',

            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            },
            compress: {
                width: 1600,
                height: 1600,
                // 图片质量，只有type为`image/jpeg`的时候才有效。
                quality: 100,
                // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
                allowMagnify: false,
                // 是否允许裁剪。
                crop: false,
                // 是否保留头部meta信息。
                preserveHeaders: true
            },
            prepareNextFile : true
        });

        Page.Uploader.on( 'fileQueued', function( files ) {
            var _postFiles = function() {
                Page.Uploader.makeThumb( files, function( error, ret ) {
                    if ( error ) {
                        // console.log('error');
                    } else {
                        var _tile = $('.photo-tile-tpl').clone().removeClass(
                                'photo-tile-tpl').attr('data-finished', '0');
                        _tile.attr('data-file-id', files.id);
                        _tile.find('.photo').css('background-image', 'url(' + ret + ')');
                        _tile.insertBefore('#pickfiles');
                        _tile.removeClass('hidden');
                    }
                }, 154, 160);
            };

            _postFiles();
        });


        Page.Uploader.on('uploadStart', function(file) {

            Page.disableDoneButton();
            // var _tile = $(".photo-tile[data-file-id=f-" + file.id + "]");
            // _startFakeUploadProcess(tile, parseInt(file.size / 5000));

        });


        Page.Uploader.on( 'uploadProgress', function( file, percentage ) {
            var _tile = $(".photo-tile[data-file-id=" + file.id + "]");
            _updateUploadProcess(_tile, parseInt(percentage*100));
        });


        Page.Uploader.on( 'uploadSuccess', function( file, response ) {
            var json = response;
            var _tile = $(".photo-tile[data-file-id=" + file.id + "]");
            
            _tile.find(".photo").attr('data-src', json.photo_url);
            // tile.find(".photo").attr('data-src', json.thumbnail_url);
            _tile.find(".btn-del").attr("data-del-url", json.delete_url);
            _tile.attr({
                'data-wp-id': json.encrypted_id,
                'data-finished': '1'
            }).removeClass('photo-tile-progress');

            Page.refreshDoneButton();
        });

        Page.Uploader.on('uploadError', function(file,reason) {
            var msg = "照片" + file.name + "上传失败，请重新上传。";
            msg += "(" + reason + ")";
            alert(msg);
            var _tile = $(".photo-tile[data-file-id=" + file.id + "]");
            _tile.find(".retry").show();
            function retryUpload (e) {
                e.preventDefault();
                _tile.find(".retry").fadeOut("slow", function() {
                    _tile.find(".progress-text").text("0%");
                    _tile.find(".progress-bar").css("height", "100%");
                    Page.Uploader.retry(file);
                    Page.refreshDoneButton();
                });
            }
            _tile.find(".retry").on('click', retryUpload);
        });
        Page.Uploader.on('error', function(type, file) {
            if(type == 'F_DUPLICATE'){
                alert('照片:' + file.name + ' 已上传');
            }
        });
    },
    initGPSEvents:function () {
        bt.gmap.initMapScript(function() {
            var options = {
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            Page.Map = new google.maps.Map(document.getElementById("gps-map"), options);
        });

        var _dealWithFailedGPSUpload = function() {
            $("#map").hide();
            Page.refreshDoneButton();
        };

        $("#gpsfile").ajaxForm({
            beforeSubmit: function() {
                $("#map").show();
                bt.gmap.refreshMap(Page.Map);
            },
            success: function(resp, statusText, xhr, $form) {
                try {
                    var result = bt.misc.parseGPS(resp);
                } catch (err) {
                    result = '';
                }
                if(!result) {
                    alert("GPS文件格式错误。");
                    _dealWithFailedGPSUpload();
                    return;
                }
                Page.GPSPoints = result[0];
                Page.GPSBounds = result[1];

                Page.Poly = new google.maps.Polyline({
                    // use your own style here
                    path: Page.GPSPoints,
                    clickable: false,
                    strokeColor: "#0695f8",
                    strokeWeight: 4,
                    strokeOpacity: .7
                });

                Page.Poly.setMap(Page.Map);
                // fit bounds to track
                Page.Map.fitBounds(Page.GPSBounds);

                Page.refreshDoneButton();
                $('#gpsfile .gpsfile-input').val('');
            },
            error: function() {
                alert("请求出错，请重试");
                _dealWithFailedGPSUpload();
            }
        });

        function _deleteGPSMap (e) {
            e.preventDefault();
            var _message = '删除 GPS 文件？';
            var _confirm = window.confirm(_message);
            if ( !_confirm ) {
                return;
            }
            if(Page.Poly) {
                Page.Poly.setMap(null);
                Page.Poly = null;
            }
            Page.GPSPoints = null;
            Page.GPSBounds = null;
            $("#map").hide();
            Page.refreshDoneButton();
        }

        $('#gpsfile .gpsfile-input').change(function(event) {
            try {
                $("#map").show();
                $("#gpsfile").submit();
            } catch (err) {
                $("#map").hide();
                alert(err);
                _dealWithFailedGPSUpload();
            }
        });

        $('#btn-del-map').on('click', _deleteGPSMap);
    },
    initGotoNext: function () {
        function _nextStep (e) {
            if($(this).hasClass("disabled")) {
                return false;
            }
            $(this).hide();
            $('#step-loading').show();
            var data = bt.misc.initPostData();
            var ids = [];
            //Collect self-only waypoint IDs
            $(".photo-tile[data-privacy=2]").each(function(index, el) {
                var _id = $(this).attr("data-wp-id");
                if(_id) {
                    ids.push(_id);
                }
            });
            data["self_ids"] = ids;

            ids = [];
            //Collect friends-only waypoint IDs
            $(".photo-tile[data-privacy=1]").each(function(index, el) {
                var _id = $(this).attr("data-wp-id");
                if(_id) {
                    ids.push(_id);
                }
            });
            data["pri_ids"] = ids;

            ids = [];
            //Collect public waypoint IDs
            $(".photo-tile[data-privacy=0]").each(function(index, el) {
                var _id = $(this).attr("data-wp-id");
                if(_id) {
                    ids.push(_id);
                }
            });
            data["pub_ids"] = ids;

            //Collect GPS track points
            if(Page.GPSPoints) {
                var tracks = [];
                $.each(Page.GPSPoints, function(index, value) {
                    var track = [
                        value.lat(),
                        value.lng(),
                        value.time
                    ];
                    tracks.push(track);
                });
                data["track_count"] = tracks.length;
                data["tracks"] = tracks;
            }

            data["timezone"] = $("#timezone").val();

            $.ajax({
                url: $(this).attr("href"),
                type: "POST",
                data: data,
                success: function(resp) {
                    if(!resp.error) {
                        $(window.location).attr("href", resp.new_edit_link);
                    } else {
                        $(this).removeClass("disabled").show();
                        $('#step-loading').hide();
                    }
                }
            });
            return false;
        }
        $("#btn-next").on('click', _nextStep);
    }
};

$(function(){
    Page.initPhotoEvents();
    Page.initUploadEvents();
    Page.initGPSEvents();
    Page.initGotoNext();
});
